package com.meizhao.api.service;

import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import com.meizhao.api.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Collection;
import java.util.function.Function;

@Service
public class DbService {

    private Session session;

    @Autowired
    public DbService(Session session){
        this.session = session;
    }

    public Object exec(Function<Session, Object> function){
        try{
            session.beginTransaction();
            Object i = function.apply(session);
            session.commit();
            return i;
        }catch (SQLException e){
            session.quietRollback();
            return ResultCode.EXCEPTION.getCode();
        }
    }

    public Integer insert(Entity entity){
        return (Integer)exec(session -> {
            try {
                return session.insert(entity);
            } catch (SQLException e) {
                e.printStackTrace();
                return ResultCode.EXCEPTION.getCode();
            }
        });
    }

    public int[] insertBatch(Collection<Entity> collection){
        return (int[])exec(session -> {
            try {
                return session.insert(collection);
            } catch (SQLException e) {
                e.printStackTrace();
                return ResultCode.EXCEPTION.getCode();
            }
        });
    }
    

    public Integer delete(Entity entity){
        return (Integer)exec(session -> {
            try {
                return session.del(entity);
            } catch (SQLException e) {
                e.printStackTrace();
                return ResultCode.EXCEPTION.getCode();
            }
        });
    }

    public Integer update(Entity entity, Entity where){
        return (Integer)exec(session -> {
            try {
                return session.update(entity,where);
            } catch (SQLException e) {
                e.printStackTrace();
                return ResultCode.EXCEPTION.getCode();
            }
        });
    }

}
